/**
 * 2016，thor.com，all rights reserved。
 * 
 * Project：		palmmall-core
 * Filename：	AStatementServiceImpl.java
 * Created：		2016年7月31日
 * Creator：		wolv
 */
package com.thor.palmmall.rest.banlancebill;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfLine;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.thor.commons.entity.UCN;
import com.thor.commons.exception.ThorServiceException;
import com.thor.commons.util.StringUtil;
import com.thor.palmmall.dao.banlancebill.BanlanceBillDao;
import com.thor.palmmall.dao.option.Option;
import com.thor.palmmall.dao.option.OptionDao;
import com.thor.palmmall.rest.balancebill.BanlanceBill;
import com.thor.palmmall.rest.balancebill.BanlanceBillDetail;
import com.thor.palmmall.rest.balancebill.BillQueryParam;
import com.thor.palmmall.rest.balancebill.CAApiConfig;
import com.thor.palmmall.rest.balancebill.RSBanlanceBillService;
import com.thor.palmmall.rest.balancebill.cainterface.CaContracResponse;
import com.thor.palmmall.rest.common.AUserGroupLoadParam;
import com.thor.palmmall.rest.common.SUserGroupLoadParamConverter;
import com.thor.palmmall.rest.contract.AContract;
import com.thor.palmmall.rest.statement.AQueryByContractParam;
import com.thor.palmmall.rest.statement.AStatement;
import com.thor.palmmall.rest.statement.ASubjectDetail;
import com.thor.palmmall.rest.statement.converter.AStatementConverter;
import com.thor.palmmall.rest.statement.converter.SQueryByContractParamConverter;
import com.thor.palmmall.rest.tenant.ATenant;
import com.thor.palmmall.rest.tenant.converter.ATenantConverter;
import com.thor.palmmall.spi.common.SResponse;
import com.thor.palmmall.spi.contract.SContractService;
import com.thor.palmmall.spi.statement.SStatement;
import com.thor.palmmall.spi.statement.SStatementService;
import com.thor.palmmall.spi.tenant.STenant;
import com.thor.palmmall.spi.tenant.STenantService;
import com.thor.palmmall.util.http.FileUtil;
import com.thor.palmmall.util.http.HttpRequestUtil;
import com.thor.palmmall.util.http.NativeEspHttpClient;
import com.thor.trans.ThorTX;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @author Vergar
 *
 */
public class RsBanlanceBillServiceImpl implements RSBanlanceBillService {

  @Autowired
  private SStatementService sStatementService;
  @Autowired
  private BanlanceBillDao banlanceBillDao;
  @Autowired
  private CAApiConfig caApiConfig;
  @Autowired
  private STenantService tenantService;
  @Autowired
  private OptionDao optionDao;
  
  private final String CA_CREATE_CONTRACT = "/contract/create";//ca创建合同接口
  private final String CA_SIGN_CONTRACT = "/contract/sign";//ca签署合同接口
  
  @Override
  public String getAttachments(String enterprise) throws ThorServiceException {
    Option option = optionDao.getOption(enterprise, "attachment");
    if(option != null){
      return option.getOptionValue();
    }
    return "";
  }

  @Override
  public List<BanlanceBill> query(BillQueryParam billQueryParam) throws Exception {
    // 判断查询条件中有几个账单日期
    List<String> billSettles = shorSettle(billQueryParam.getBeginSettle(),
        billQueryParam.getEndSettle());
    // 根据项目id获取商户详情
    ATenant aTenant = getCreATenant(billQueryParam);
    if(aTenant == null){
      throw new ThorServiceException("无法查询到商户");
    }
    List<BanlanceBill> banlanceBills = null;
    try {
      // 循环账单日期，查询账单，保存或更新到数据库
      for (String billSettle : billSettles) {
        // saveOrUpdateBill(billQueryParam,billSettle,aContract);
        saveOrUpdateBill(billQueryParam, billSettle,aTenant);
      }
      // 返回接口数据
      banlanceBills = banlanceBillDao.getBanlanceBills(billQueryParam,
          billSettles);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return banlanceBills;
  }
  
  /**
   * 获取商户信息
   * @param billQueryParam
   * @return
   */
  private ATenant getCreATenant(BillQueryParam billQueryParam) {
    AUserGroupLoadParam queryParam = new AUserGroupLoadParam();
    List<String> stores = new ArrayList<String>();
    stores.add(billQueryParam.getStoreId());
    queryParam.setStores(stores);
    queryParam.setUserGroups(billQueryParam.getUserGroups());
    SResponse<STenant> resp = tenantService.get(billQueryParam.getTenantId(),
        SUserGroupLoadParamConverter.getInstance().convert(queryParam));
    if (resp.isSuccess()) {
      return ATenantConverter.getInstance().convert(resp.getBody());
    }else{
      return null;
    }
    
  }

  private void saveOrUpdateBill(BillQueryParam billQueryParam, String billSettle, ATenant aTenant)  throws Exception  {
    try {
      AStatement aStatement = null;
      AQueryByContractParam aparam = new AQueryByContractParam();
      aparam.setBeginSettle(billSettle);
      aparam.setEndSettle(billSettle);
      aparam.setContract(billQueryParam.getContracts());
      aparam.setUserGroups(billQueryParam.getUserGroups());
      if (!StringUtil.isNullOrBlank(billQueryParam.getContracts())) {
        aparam.getStores().add(billQueryParam.getStoreId());
      }
      // 调cre接口，获取对账单数据
      SResponse<SStatement> sResponse = sStatementService
          .queryByContract(SQueryByContractParamConverter.getInstance().convert(aparam));
      if (sResponse.isSuccess()) {
        aStatement = AStatementConverter.getInstance().convert(sResponse.getBody());
      }
      if (aStatement != null && aStatement.getContract() != null ) {
        // 保存或更新记录
        banlanceBillDao.save(transBill(aStatement, billSettle,aTenant,billQueryParam.getContractType()));
      }
    } catch (Exception e) {
      throw e;
    }

  }

  private BanlanceBill transBill(AStatement aStatement, String billSettle, ATenant aTenant,String contractType) throws Exception {
    try {
      BanlanceBill banlanceBill = new BanlanceBill();
      UCN aContract = aStatement.getContract();
      String billId = banlanceBillDao.getBanlancebillByCode(aContract.getCode(), billSettle);
      if (billId != null) {
        banlanceBill.setUuid(billId);
      }
      String contractCode = aContract.getCode();
      String billNo = billSettle + contractCode.substring(contractCode.length() - 5);
      banlanceBill.setBillNo(billNo);
      banlanceBill.setContract(aStatement.getContract());
      banlanceBill.setStore(aStatement.getStore());
      banlanceBill.setTenant(aStatement.getTenant());
      banlanceBill.setPayTotal(aStatement.getPayTotal());
      banlanceBill.setPayedTotal(aStatement.getPayedTotal());
      banlanceBill.setUnpayedTotal(aStatement.getUnpayedTotal());
      banlanceBill.setLegalName(aTenant.getLegalName());
      banlanceBill.setAddress(aTenant.getAddress());
      banlanceBill.setTaxCode(aTenant.getTaxCode());
      banlanceBill.setLegalPersion(aTenant.getLegalPersion());
      banlanceBill.setPhone(aTenant.getPhone());
      banlanceBill.setContractType(contractType);
      banlanceBill.setBillSettle(billSettle);
      // 如果
      if (aStatement.getUnpayedTotal().compareTo(new BigDecimal("0")) > 0) {
        banlanceBill.setBillState("unpaid");
      } else if (aStatement.getUnpayedTotal().compareTo(new BigDecimal("0")) == 0) {
        banlanceBill.setBillState("confirmed");
      }
      List<ASubjectDetail> subjects = aStatement.getSubjects();
      List<BanlanceBillDetail> details = tranBillDetail(subjects, billNo, banlanceBill);
      banlanceBill.setDetails(details);
      return banlanceBill;
    } catch (Exception e) {
      throw e;
    }
  }
  /*
   * private BanlanceBill transBill(AStatement aStatement, AContract aContract,
   * String billSettle) { BanlanceBill banlanceBill = new BanlanceBill(); String
   * billId =
   * banlanceBillDao.getBanlancebillByCode(aContract.getCode(),billSettle);
   * if(billId != null){ banlanceBill.setUuid(billId); } String contractCode =
   * aContract.getCode(); String billNo = billSettle +
   * contractCode.substring(contractCode.length()-5);
   * banlanceBill.setBillNo(billNo);
   * banlanceBill.setContract(aStatement.getContract());
   * banlanceBill.setStore(aStatement.getStore());
   * banlanceBill.setTenant(aStatement.getTenant());
   * banlanceBill.setPayTotal(aStatement.getPayTotal());
   * banlanceBill.setPayedTotal(aStatement.getPayedTotal());
   * banlanceBill.setUnpayedTotal(aStatement.getUnpayedTotal()); //如果
   * if(aStatement.getUnpayedTotal().compareTo(new BigDecimal("0")) > 0 ){
   * banlanceBill.setBillState("unpaid"); }else
   * if(aStatement.getUnpayedTotal().compareTo(new BigDecimal("0")) == 0){
   * banlanceBill.setBillState("confirmed"); }
   * banlanceBill.setBillSettle(billSettle); List<ASubjectDetail> subjects =
   * aStatement.getSubjects() ; List<BanlanceBillDetail> details =
   * tranBillDetail(subjects,billNo,banlanceBill);
   * banlanceBill.setDetails(details); return banlanceBill; }
   */

  private List<BanlanceBillDetail> tranBillDetail(List<ASubjectDetail> subjects, String billNo,
      BanlanceBill banlanceBill) throws Exception {
    List<BanlanceBillDetail> details = new ArrayList<BanlanceBillDetail>();
    List<String> actIds = new ArrayList<String>();
    for (ASubjectDetail aSubjectDetail : subjects) {
      actIds.add(aSubjectDetail.getAccId());
    }
    banlanceBillDao.deleteOldDetail(actIds);
    try {
      for (ASubjectDetail aSubjectDetail : subjects) {
//        BanlanceBillDetail billDetail = banlanceBillDao.getDetailByAccId(aSubjectDetail.getAccId());
//        if(billDetail == null){
//          billDetail = new BanlanceBillDetail();
//        }
        BanlanceBillDetail billDetail = new BanlanceBillDetail();
        billDetail.setBill(banlanceBill);
        billDetail.setBillNo(billNo);
        billDetail.setSubject(aSubjectDetail.getSubject());
        billDetail.setBeginDate(aSubjectDetail.getBeginDate());
        billDetail.setEndDate(aSubjectDetail.getEndDate());
        billDetail.setPayTotal(aSubjectDetail.getPayTotal());
        billDetail.setPayedTotal(aSubjectDetail.getPayedTotal());
        billDetail.setUnpayedTotal(aSubjectDetail.getUnpayedTotal());
        billDetail.setConfirmed(aSubjectDetail.getConfirmed());
        billDetail.setAccId(aSubjectDetail.getAccId());
        details.add(billDetail);
      }
    } catch (Exception e) {
      throw e;
    }
    return details;
  }

  private List<String> shorSettle(String beginSettle, String endSettle) {
    List<String> settles = new ArrayList<String>();
    try {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
      Calendar c = Calendar.getInstance();
      c.setTime(sdf.parse(endSettle));
      int year1 = c.get(Calendar.YEAR);
      int month1 = c.get(Calendar.MONTH);

      c.setTime(sdf.parse(beginSettle));
      int year2 = c.get(Calendar.YEAR);
      int month2 = c.get(Calendar.MONTH);

      int result;
      if (year1 == year2) {
        result = month1 - month2;
      } else {
        result = 12 * (year1 - year2) + month1 - month2;
      }
      settles.add(beginSettle);
      if (result > 1) {
        for (int i = 1; i < result; i++) {
          c.setTime(sdf.parse(beginSettle));
          c.add(Calendar.MONTH, 1);
          settles.add(sdf.format(c.getTime()));
        }
      }
    } catch (ParseException e) {
      e.printStackTrace();
    }
    return settles;
  }

  @Override
  public List<BanlanceBillDetail> getDetails(String billUuid) throws ThorServiceException {
    List<BanlanceBillDetail> list = banlanceBillDao.getBanlanceBills(billUuid);
    return list;
  }
  
  private void invokeCreatePDF(BanlanceBill bill) throws Exception {
    //step 1 : 创建合同接口 
    JSONObject contractJson = buildCreateContractJson(bill);
    String url = caApiConfig.getApiPath() + CA_CREATE_CONTRACT;
    NativeEspHttpClient espHttpClient = new NativeEspHttpClient();
    String strJsonRespData = espHttpClient.postSignedJson(url, contractJson, caApiConfig.getApiSecret());
    JSONObject jsonResp =  JSONObject.fromObject(strJsonRespData);
    if (jsonResp.getBoolean("isOk")) {
      //step 2 :签章，返回base64的pdf
      JSONObject contract = jsonResp.getJSONObject("contract");
      String contractId = contract.getString("contractId");
      
      JSONObject signJson = buildSignJson(contractId);
      String signUrl = caApiConfig.getApiPath() + CA_SIGN_CONTRACT;
      String signRespData = espHttpClient.postSignedJson(signUrl,signJson , caApiConfig.getApiSecret());
      JSONObject signResult = JSONObject.fromObject(signRespData);
      if(signResult.getBoolean("isOk")){
        JSONObject contractRes =signResult.getJSONObject("contract");
        String doc = contractRes.getString("doc");
        String  path = caApiConfig.getFilePath() + File.separatorChar + bill.getBillSettle() + File.separatorChar + bill.getContract().getCode() + ".pdf";
        FileUtil.decoderBase64File(doc,path);
      }
      
      
    }
   
    
  }
  
  /**
   * 签署合同---请求json
   * @param contractId
   * @param config
   * @return
   */
  private JSONObject buildSignJson(String contractId) {
    JSONObject signJson = new JSONObject();
    signJson.put("apiId", caApiConfig.getApiId());
    signJson.put("timestamp",  System.currentTimeMillis());
    signJson.put("contractId", contractId);
    signJson.put("userId", caApiConfig.getUserId());
    signJson.put("docRequired", true);
    return signJson;
  }

  /**
   * 创建合同 --- 请求json
   * @param bill
   * @param config
   * @return
   * @throws Exception
   */
  private JSONObject buildCreateContractJson(BanlanceBill bill)  {
    JSONObject contractJson = new JSONObject();
    try {
      String filePath = caApiConfig.getFilePath() + File.separatorChar + bill.getBillSettle() + File.separatorChar + bill.getContract().getCode() + ".pdf";
      contractJson.put("apiId", caApiConfig.getApiId());
      contractJson.put("timestamp", System.currentTimeMillis());
      
      JSONObject orderJson = new JSONObject();
      orderJson.put("title", bill.getBillNo() + bill.getTenant().getCode());
      orderJson.put("docNum", bill.getBillNo());
      orderJson.put("docType", "pdf");
      orderJson.put("doc", FileUtil.encodeBase64File(filePath));
      
      JSONArray signatures = new JSONArray();
      JSONObject signature = new JSONObject();
      signature.put("userId", caApiConfig.getUserId());
      signature.put("page", caApiConfig.getPage());
      signature.put("positionX", caApiConfig.getPositionX());
      signature.put("positionY", caApiConfig.getPositionY());
      signatures.add(signature);
      orderJson.put("signatures", signatures.toString());
      
      contractJson.put("contract", orderJson);
      contractJson.put("docRequired", true);
     
    } catch (Exception e) {
      e.printStackTrace();
    }
    return contractJson;
  }

  /**
   * test
   */
  private void testinvokeCreatePDF()  {
   String apiSecret = "638db0abfb6877bf3d130399c792155e";
    try {
      long timeStamp = System.currentTimeMillis();
      JSONObject contractJson = new JSONObject();
      contractJson.put("apiId", "zdjt");
      contractJson.put("timestamp", timeStamp);
      
      JSONObject orderJson = new JSONObject();
      orderJson.put("title", "test合同");
      orderJson.put("docNum", "20171202");
      orderJson.put("docType", "pdf");
      orderJson.put("doc", FileUtil.encodeBase64File("/Users/Luke/Desktop/test/book111.pdf"));
      
      JSONArray signatures = new JSONArray();
      JSONObject signature = new JSONObject();
      signature.put("userId", "73de4cf6-6f3e-413b-ada8-65b8d198c09e");
      signature.put("page", 1);
      signature.put("positionX", 135);
      signature.put("positionY", 135);
      signatures.add(signature);
      orderJson.put("signatures", signatures.toString());
      
      contractJson.put("contract", orderJson);
      contractJson.put("docRequired", true);
      System.out.println(contractJson.toString());
      String url = CA_CREATE_CONTRACT;
      NativeEspHttpClient espHttpClient = new NativeEspHttpClient();
      String strJsonRespData = espHttpClient.postSignedJson(url, contractJson, apiSecret);
      System.out.println(strJsonRespData);
      JSONObject result =  JSONObject.fromObject(strJsonRespData);
      JSONObject contractResult = result.getJSONObject("contract");
      
      String contractId = contractResult.getString("contractId");
//      CaContracResponse respsonse = (CaContracResponse)JSONObject.toBean(contractResult,CaContracResponse.class);
//      if(result != null && "200".equals(result.getString("code"))){
//        //解析结果
//        System.out.println(result.toString());
//        CaContracResponse respsonse = (CaContracResponse)JSONObject.toBean(result,CaContracResponse.class);
//        
//      }
      String signUrl = "http://10.130.12.31:8080/esp/contract/sign";
      JSONObject signJson = new JSONObject();
      signJson.put("apiId", "zdjt");
      signJson.put("timestamp", timeStamp);
      signJson.put("contractId", contractId);
      signJson.put("userId", "73de4cf6-6f3e-413b-ada8-65b8d198c09e");
      signJson.put("docRequired", true);
//      signJson.put("authCode", "null");
//      String signJsonString = "{\"timestamp\":1524465516066L,\"apiId\":\"zdjt\",\"docRequired\":true,\"userId\":\"73de4cf6-6f3e-413b-ada8-65b8d198c09e\",\"contractId\":\"609826c4-444d-426d-b121-bbdd6cb4aaf9\",\"authCode\":\"null\"}";
//      String signJsonString = "{\"timestamp\":1524465516066L,\"apiId\":\"zdjt\",\"docRequired\":true,\"userId\":\"73de4cf6-6f3e-413b-ada8-65b8d198c09e\",\"contractId\":\"609826c4-444d-426d-b121-bbdd6cb4aaf9\"}";
//      String s = signJsonString.replaceAll(":null,", ":\"null\",");
//      JSONObject newSignJson = JSONObject.fromObject(signJsonString);
      String signRespData = espHttpClient.postSignedJson(signUrl,signJson , apiSecret);
      System.out.println(signRespData);
      JSONObject docResult = JSONObject.fromObject(signRespData);
      JSONObject contractR =docResult.getJSONObject("contract");
      String doc = contractR.getString("doc");
      String  path = "/Users/Luke/Desktop/test/book222.pdf";
      FileUtil.decoderBase64File(doc,path);
      
    } catch (Exception e) {
      e.printStackTrace();
    }
    
  }

  private void createPdfBill(BanlanceBill bill) {
    try {
      List<BanlanceBillDetail> list = bill.getDetails();
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      File fileCreate = new File(caApiConfig.getFilePath() + File.separatorChar + bill.getBillSettle() + File.separatorChar + bill.getContract().getCode() + ".pdf");
      if (!fileCreate.getParentFile().exists()){
        fileCreate.getParentFile().mkdirs();
      }
      Document document = new Document(PageSize.A4.rotate());
      PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileCreate));
      document.open();

      BaseFont bfChi = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
      Font fontChi = new Font(bfChi, 26, Font.NORMAL);
      BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);  
      
      //字体样式 大小
      com.itextpdf.text.Font FontChinese24 = new com.itextpdf.text.Font(bfChinese, 24, com.itextpdf.text.Font.BOLD);
      com.itextpdf.text.Font FontChinese18 = new com.itextpdf.text.Font(bfChinese, 18, com.itextpdf.text.Font.BOLD); 
      com.itextpdf.text.Font FontChinese16 = new com.itextpdf.text.Font(bfChinese, 16, com.itextpdf.text.Font.BOLD);
      com.itextpdf.text.Font FontChinese12 = new com.itextpdf.text.Font(bfChinese, 12, com.itextpdf.text.Font.NORMAL);
      com.itextpdf.text.Font FontChinese11Bold = new com.itextpdf.text.Font(bfChinese, 11, com.itextpdf.text.Font.BOLD);
      com.itextpdf.text.Font FontChinese11 = new com.itextpdf.text.Font(bfChinese, 11, com.itextpdf.text.Font.ITALIC);
      com.itextpdf.text.Font FontChinese11Normal = new com.itextpdf.text.Font(bfChinese, 9, com.itextpdf.text.Font.NORMAL);

      //标题
      Paragraph paragraph = new Paragraph("缴费通知单", fontChi);
      paragraph.setAlignment(Element.ALIGN_LEFT);
      document.add(paragraph);
      
      fontChi.setSize(20);
      
      //table1  Payment Statement
      PdfPTable table1 = new PdfPTable(2);
      int width1[] = {40,60};
      table1.setWidths(width1); 
      PdfPCell cell11 = new PdfPCell(new Paragraph("Payment Statement",FontChinese11));
      PdfPCell cell12 = new PdfPCell(new Paragraph("租户组织结构代码证号:"+bill.getTaxCode(),FontChinese11Normal));
      cell11.setBorder(0);
      cell12.setBorder(0);
      table1.addCell(cell11);
      table1.addCell(cell12);
      document.add(table1);
      
      //空行
      Paragraph blankRow31 = new Paragraph(18f, " ", FontChinese11Normal); 
      document.add(blankRow31);
      //合同详情
      PdfPTable table5 = new PdfPTable(1);
      PdfPCell cell51 = new PdfPCell(new Paragraph("邮编:" + bill.getTaxCode(),FontChinese11Normal));
      cell51.setBorder(0);
      table5.addCell(cell51);
      document.add(table5);
      
      //table5
      PdfPTable table0 = new PdfPTable(1);
      PdfPCell cell01 = new PdfPCell(new Paragraph("地址:" + bill.getAddress(),FontChinese11Normal));
      cell01.setBorder(0);
      table0.addCell(cell01);
      document.add(table0);
     
      //table5
      PdfPTable table4 = new PdfPTable(1);
      PdfPCell cell41 = new PdfPCell(new Paragraph("公司名称:" + bill.getLegalName(),FontChinese11Normal));
      cell41.setBorder(0);
      table4.addCell(cell41);
      document.add(table4);
      
      //table6
      PdfPTable table6 = new PdfPTable(1);
      PdfPCell cell61 = new PdfPCell(new Paragraph("收件人:",FontChinese11Normal));
      cell61.setBorder(0);
      table6.addCell(cell61);
      document.add(table6);
      
      PdfPTable table2 = new PdfPTable(2);
      int width2[] = {40,35};
      table2.setWidths(width2); 
      PdfPCell cell21 = new PdfPCell(new Paragraph("电话:" + bill.getPhone(),FontChinese11Normal));
      PdfPCell cell22 = new PdfPCell(new Paragraph("租户:",FontChinese11Normal));
      cell21.setBorder(0);
      cell22.setBorder(0);
      table2.addCell(cell21);
      table2.addCell(cell22);
      document.add(table2);
      
      //table7
      PdfPTable table7 = new PdfPTable(3);
      int width7[] = {40,35,30};
      table7.setWidths(width7); 
      PdfPCell cell71 = new PdfPCell(new Paragraph("合同号:" + bill.getContract().getCode(),FontChinese11Normal));
      PdfPCell cell72 = new PdfPCell(new Paragraph("店铺:" + bill.getTenant().getName(),FontChinese11Normal));
      PdfPCell cell73 = new PdfPCell(new Paragraph("日期:" + bill.getBillSettle(),FontChinese11Normal));
      cell71.setBorder(0);
      cell72.setBorder(0);
      cell73.setBorder(0);
      table7.addCell(cell71);
      table7.addCell(cell72);
      table7.addCell(cell73);
      document.add(table7);
      
      //table8
      PdfPTable table8 = new PdfPTable(3);
      int width8[] = {40,35,30};
      table8.setWidths(width8); 
      PdfPCell cell81 = new PdfPCell(new Paragraph("合同类型:" + bill.getContractType(),FontChinese11Normal));
      PdfPCell cell82 = new PdfPCell(new Paragraph("店招:" + bill.getContract().getName(),FontChinese11Normal));
      PdfPCell cell83 = new PdfPCell(new Paragraph("*账单号:" + bill.getBillNo(),FontChinese11Normal));
      cell81.setBorder(0);
      cell82.setBorder(0);
      cell83.setBorder(0);
      table8.addCell(cell81);
      table8.addCell(cell82);
      table8.addCell(cell83);
      document.add(table8);
      
      //项目
//      PdfPTable table9 = new PdfPTable(4);
//      int width9[] = {40,35,25,30};
//      table9.setWidths(width9); 
//      PdfPCell cell91 = new PdfPCell(new Paragraph("项目(ITEM)："+"XXX",FontChinese11));
//      PdfPCell cell92 = new PdfPCell(new Paragraph("起止日期/发布时间："+"2011-11-11",FontChinese11));
//      PdfPCell cell93 = new PdfPCell(new Paragraph("报销单号："+"123456789",FontChinese11));
//      PdfPCell cell94 = new PdfPCell(new Paragraph("报销单号："+"123456789",FontChinese11));
//      cell91.setBorder(0);
//      cell92.setBorder(0);
//      cell93.setBorder(0);
//      cell94.setBorder(0);
//      table9.addCell(cell91);
//      table9.addCell(cell92);
//      table9.addCell(cell93);
//      table9.addCell(cell94);
//      document.add(table9);
      
//    document.add(new Chunk("------------------------------------------------------------"));
      PdfPTable table = new PdfPTable(4);
      table.setSpacingBefore(20f);
      table.setSpacingAfter(10f);
      table.setWidthPercentage(100);
      float[] columnWidth = {
          95, 135, 60,135
      };
//          95, 135, 60, 75, 60, 60, 60, 75, 140 };
      table.setTotalWidth(columnWidth);
      table.setLockedWidth(true);
      table.addCell(new Paragraph("项目(ITEM)", FontChinese11));
      table.addCell(new Paragraph("起止日期/发布时间", FontChinese11));
      table.addCell(new Paragraph("参考金额(RMB)", FontChinese11));
      table.addCell(new Paragraph("应收金额(RMB)", FontChinese11));
      for (BanlanceBillDetail detail : list) {
        table.addCell(new Paragraph(detail.getSubject().getName(), FontChinese11));
        table.addCell(new Paragraph(detail.getBeginDate().toString(), FontChinese11));
        table.addCell(new Paragraph("", FontChinese11));
        table.addCell(new Paragraph(detail.getPayedTotal().toString(), FontChinese11));
      }
      document.add(table);
//      document.add(new Chunk("------------------------------------------------------------"));
      

      PdfPTable table10 = new PdfPTable(2);
      int width10[] = {40,35};
      table10.setWidths(width10); 
      PdfPCell cell101 = new PdfPCell(new Paragraph("余额(+应收;-应付) Balance(+AR;-AP)" ,FontChinese11Normal));
      PdfPCell cell102 = new PdfPCell(new Paragraph(bill.getPayTotal().toString(),FontChinese11Normal));
      cell101.setBorder(0);
      cell102.setBorder(0);
      table10.addCell(cell101);
      table10.addCell(cell102);
      document.add(table10);
      
      
      
      document.close();
      writer.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (DocumentException e) {
      e.printStackTrace();
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

  }

  @Override
  public void confirmSubjects(List<String> accIds) throws ThorServiceException {
//     SResponse<Void> sResponse =
//     sStatementService.confirmStatementSubjects(accIds);
//     if (!sResponse.isSuccess()){
//       throw new ThorServiceException(sResponse.getMessage());
//     }
     //校验状态
     for (String actId : accIds) {
       BanlanceBillDetail billDetail = banlanceBillDao.getDetailByAccId(actId);
       if(billDetail.getConfirmed()){
         throw new ThorServiceException("确认失败，存在已确认的明细记录");
       }
     }
    
     BanlanceBill bill = banlanceBillDao.getBillByAccId(accIds.get(0));
     try {
       //创建缴费通知单pdf
       createPdfBill(bill);
       //调用ca接口 创建签章pdf文件
       invokeCreatePDF(bill);
     } catch (Exception e) {
      e.printStackTrace();
     }
  }

}
